<template>
  <div ref="chartRef" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import { ref, onMounted, watch, defineProps } from 'vue';
import * as echarts from 'echarts';
import { darkTheme, lightTheme } from './chartThemes';

const props = defineProps({
  chartData: {
    type: [Object, Array],
    default: () => ({ labels: [], values: [] })
  },
  chartType: {
    type: String,
    default: 'normal' // 'normal' or 'stacked'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
   theme: {
    type: String,
    default: 'light'
  }
});

const chartRef = ref(null);
let myChart = null;

const themes = {
  dark: darkTheme,
  light: lightTheme
};

const initChart = () => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value, props.theme === 'dark' ? themes.dark : null);
    setOptions(props.chartData);
  }
};

const setOptions = (data) => {
  if (!myChart || !data) return;

  let options;

  if (props.chartType === 'stacked') {
    const labels = data.map(item => item.name);
    const occupiedData = data.map(item => item.occupied_area);
    const vacantData = data.map(item => (item.total_area - item.occupied_area).toFixed(2));
    
    options = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: (params) => {
          const dataItem = data.find(d => d.name === params[0].axisValue);
          if (!dataItem) return '';
          const occupied = dataItem.occupied_area;
          const total = dataItem.total_area;
          const vacant = (total - occupied).toFixed(2);
          
          return `${dataItem.name}<br/>
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#00e5ff;"></span>已占用面积: ${occupied} ㎡<br/>
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:rgba(0, 229, 255, 0.3);"></span>未占用面积: ${vacant} ㎡<br/>
            <strong>总面积: ${total} ㎡</strong>`;
        }
      },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'value', splitLine: { show: false } },
      yAxis: { type: 'category', data: labels, axisTick: { show: false } },
      legend: {
        data: ['已占用面积', '未占用面积'],
        top: 'top',
        textStyle: {
          color: props.theme === 'dark' ? '#fff' : '#333'
        }
      },
      series: [
        {
          name: '已占用面积',
          type: 'bar',
          stack: 'total',
          emphasis: { focus: 'series' },
          data: occupiedData,
          itemStyle: { color: '#00e5ff' }
        },
        {
          name: '未占用面积',
          type: 'bar',
          stack: 'total',
          emphasis: { focus: 'series' },
          data: vacantData,
          itemStyle: { color: 'rgba(0, 229, 255, 0.3)' }
        }
      ]
    };
  } else {
    // 增强版普通条形图
    options = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
          shadowStyle: {
            color: 'rgba(0, 162, 255, 0.1)'
          }
        },
        backgroundColor: 'rgba(0, 21, 53, 0.85)',
        borderColor: '#00a2ff',
        borderWidth: 1,
        textStyle: {
          color: '#fff'
        },
        formatter: (params) => {
          const dataIndex = params[0].dataIndex;
          const name = data.labels[dataIndex];
          const value = params[0].value;
          const percent = ((value / Math.max(...data.values)) * 100).toFixed(1);
          
          return `<div style="padding: 3px 8px">
            <div style="font-weight: bold; margin-bottom: 5px">${name}</div>
            <div>故障率: <span style="color: #ff4d4f; font-weight: bold">${value}%</span></div>
            <div>占比: ${percent}%</div>
          </div>`;
        }
      },
      grid: {
        left: '3%',
        right: '10%',  // 增加右侧空间以容纳数据标签
        bottom: '3%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        splitLine: { 
          show: true,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(0, 162, 255, 0.1)'
          }
        },
        axisLabel: {
          formatter: '{value}%',
          color: props.theme === 'dark' ? '#aed4ff' : '#666'
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(0, 162, 255, 0.3)'
          }
        }
      },
      yAxis: {
        type: 'category',
        data: data.labels,
        axisTick: { show: false },
        axisLine: {
          lineStyle: {
            color: 'rgba(0, 162, 255, 0.3)'
          }
        },
        axisLabel: {
          color: props.theme === 'dark' ? '#aed4ff' : '#666',
          formatter: (value) => {
            // 如果文本太长，截断并添加省略号
            if (value.length > 10) {
              return value.substring(0, 10) + '...';
            }
            return value;
          }
        }
      },
      series: [{
        name: '故障率',
        type: 'bar',
        barWidth: '60%',  // 调整条形宽度
        data: data.values,
        itemStyle: {
          color: (params) => {
            // 根据值的大小创建不同的渐变色
            const value = params.value;
            const max = Math.max(...data.values);
            const ratio = value / max;
            
            // 颜色从蓝色到红色的渐变
            let startColor, endColor;
            if (ratio < 0.3) {
              startColor = '#00e5ff';
              endColor = '#00a2ff';
            } else if (ratio < 0.7) {
              startColor = '#ffbb00';
              endColor = '#ff9500';
            } else {
              startColor = '#ff4d4f';
              endColor = '#ff1e1e';
            }
            
            return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: startColor },
              { offset: 1, color: endColor }
            ]);
          },
          borderRadius: [0, 4, 4, 0],  // 右侧圆角
          shadowColor: 'rgba(0, 162, 255, 0.3)',
          shadowBlur: 10
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}%',
          color: props.theme === 'dark' ? '#fff' : '#333',
          fontWeight: 'bold'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 20,
            shadowColor: 'rgba(0, 229, 255, 0.5)'
          },
          label: {
            color: '#00e5ff'
          }
        },
        // 添加动画效果
        animationDelay: function(idx) {
          return idx * 100;
        },
        animationDuration: 1500,
        animationEasing: 'elasticOut'
      }]
    };
  }
  myChart.setOption(options);
};

watch(() => props.chartData, (newData) => {
  if(myChart) {
    setOptions(newData);
  }
}, { deep: true });

watch(() => props.theme, (newTheme) => {
    if (myChart) {
        myChart.dispose();
        initChart();
    }
});

onMounted(() => {
  initChart();
});
</script> 